<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/23
 * Time: 下午1:36
 */

namespace api\modules\v1\controllers;

use common\helpers\predis\Predis;
use common\helpers\sms\Sms;
use common\jobs\SmsJob;
use yii;

class SmsCodeController extends yii\web\Controller
{
    public $enableCsrfValidation = false;

    public function actionSend()
    {
        $phone = Yii::$app->request->post('phone');
        if (empty($phone)) {
            return ['code' => 0, 'message' => '手机号为空'];
        }
        $cacheKey = Sms::getCacheKey($phone);
        $booleanExist = Predis::getInstance()->getClient()->client->exists($cacheKey);

        if ($booleanExist) {
            $second = Predis::getInstance()->getClient()->client->ttl($cacheKey);
            $minute = ceil($second / 60);
            if ($minute == 0) {
                $minute = 1;
            }
            return ['code' => 0, 'message' => "请" . $minute . "分钟后再试"];
        }
        $code = rand(100000, 999999);

        Predis::getInstance()->getClient()->client->set($cacheKey, $code);
        Predis::getInstance()->getClient()->client->expire($cacheKey, 5 * 60);
        $dataVariables = [['Name' => '#DV_CustomizedInfo#', 'Value' => $code]];
        Yii::$app->queue_sms->push(new SmsJob([
            'phone' => $phone,
            'dataVariables' => &$dataVariables,
            'template' => '000012'
        ]));
        return ['code' => 1, 'message' => '短信已发送'];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        if (\Yii::$app->request->isOptions) {
            exit();
        }
    }
}
